package otSpaces.server;

import java.io.Serializable;

import otSpaces.server.OtSpaceManager.TSpaceManagerImpl;
import otSpaces.server.util.ManagedSingleton;
import otSpaces.server.util.ReferenceMapping;

import com.sun.sgs.app.ChannelManager;

public class OtSpacesRegistry implements Serializable, ManagedSingleton {

	private static final long serialVersionUID = 4351310524317329812L;

	public static ChannelManager locate(final String tspaceName) {

		if (tspaceName.matches(".*[^a-zA-Z0-9\\.].*")) {
			throw new IllegalArgumentException();
		} else {
			final OtSpacesRegistry registry = ManagedSingleton.Registry
					.get(OtSpacesRegistry.class);

			return registry.find(tspaceName);
		}
	}

	private final ReferenceMapping.Ref<String, OtSpaceManager> _mapRef = new ReferenceMapping.Ref<String, OtSpaceManager>(
			true);

	public OtSpaceManager find(String tspaceName) {

		if (!_mapRef.get().containsKey(tspaceName)) {
			_mapRef.get().put(tspaceName, new TSpaceManagerImpl(tspaceName));
		}

		return _mapRef.get().get(tspaceName);

	}
}